﻿using BLL;
using JLHelper;
using Microsoft.AspNetCore.Mvc;
using NetHelperCore;
using System.Diagnostics;

namespace MqttServiceManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [App_Start.CheckLocalFilter]
    public class WindowsServiceController : ControllerBase
    {
        /// <summary>
        /// 获取Windows服务名
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel GetWindowsServiceName()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                _rm.Success = 1;
                _rm.Result = ConfigBLL.Config.WindowsServiceName;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogHelper.LogType.Error, ex.Message + "---" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = ex.Message;
            }


            return _rm;
        }

        /// <summary>
        /// 获取服务是否已安装
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel IsWindowsServiceExists()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                if (WindowsServiceHelper.IsServiceIsExisted(ConfigBLL.Config.WindowsServiceName))
                {
                    _rm.Success = 1;
                    _rm.Result = true;
                }
                else
                {
                    _rm.Success = 1;
                    _rm.Result = false;
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogHelper.LogType.Error, ex.Message + "---" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = ex.Message;
            }


            return _rm;
        }

        /// <summary>
        /// 安装Windows服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel WindowsServiceInstall()
        {


            string _param = Request.Form["ParamStr"].ToString();
            if (!string.IsNullOrWhiteSpace(_param))
            {
                ConfigBLL.LoadConfig();
                JsonHelper _json = new JsonHelper(_param);
                ConfigBLL.Config.WindowsServiceName = _json.GetVar("ServiceName");
                ConfigBLL.SaveConfig();
            }
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                using (Process p = new Process())
                {
                    p.StartInfo.FileName = NetHelperCore.FileHelper.GetRunPath() + @"\Lib\WindowsService.exe";//可执行程序路径
                    p.StartInfo.Arguments = "Type=ServiceInstall ServiceName=" + ConfigBLL.Config.WindowsServiceName + " ServicePath=" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + " KillProcessID=" + Convert.ToString(System.Diagnostics.Process.GetCurrentProcess().Id) + " ServiceDescription=" + ConfigBLL.Config.WindowsServiceDescription;//参数以空格分隔，如果某个参数为空，可以传入""
                    p.StartInfo.UseShellExecute = true;//是否使用操作系统shell启动
                    p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                    p.StartInfo.Verb = "runas";
                    p.Start();
                    p.WaitForExit();
                    //正常运行结束放回代码为0
                    if (p.ExitCode == 0)
                    {
                        _rm.Success = 1;
                        _rm.Result = true;

                    }
                }
                //Environment.Exit(1);


            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogHelper.LogType.Error, ex.Message + "---" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = ex.Message;
            }


            return _rm;

        }

        /// <summary>
        /// 卸载Windows服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel WindowsServiceUnInstall()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                using (Process p = new Process())
                {
                    p.StartInfo.FileName = NetHelperCore.FileHelper.GetRunPath() + @"\Lib\WindowsService.exe";//可执行程序路径
                    p.StartInfo.Arguments = "Type=ServiceUnInstall ServiceName=" + ConfigBLL.Config.WindowsServiceName;//参数以空格分隔，如果某个参数为空，可以传入""
                    p.StartInfo.UseShellExecute = true;//是否使用操作系统shell启动
                    p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                    p.StartInfo.Verb = "runas";
                    p.Start();
                    p.WaitForExit();
                    //正常运行结束放回代码为0
                    if (p.ExitCode == 0)
                    {
                        _rm.Success = 1;
                        _rm.Result = true;
                    }
                }


            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogHelper.LogType.Error, ex.Message + "---" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = ex.Message;
            }


            return _rm;

        }

    }
}
